package cn.zhizihua.controller;

import cn.zhizihua.pojo.CartItem;
import cn.zhizihua.query.CartItemQuery;
import cn.zhizihua.service.ICartItemService;
import cn.zhizihua.vo.ResultBean;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Api(value = "购物车的API",description="购物车相关的CRUD功能")
@RestController
@RequestMapping("/cart")   //模块路径
public class CartItemController {

    @Autowired
    ICartItemService cartItemService;

    @ApiOperation(value = "保存购物车信息，有id修改，无id添加")
    @PostMapping      //  请求方式 + 请求路径   post  /cart
    public ResultBean save(@RequestBody CartItem cartItem){
        System.out.println("----CartItemController-----save--------");
        System.out.println(cartItem);
        if (cartItem.getCartId()==null){
            return cartItemService.add(cartItem);
        }
        return cartItemService.update(cartItem);
    }

    @ApiOperation(value = "删除购物车信息")
    @DeleteMapping("/{id}")   // http://localhost:8080/cartItem/1003   //  delete   /cartItem/1003
    public ResultBean del(@PathVariable("id") Integer id){
        System.out.println("-------CartItemController--------del-------------");
        System.out.println(id);
        return cartItemService.delete(id);
    }

    @ApiOperation(value = "通过id查找购物车信息")
    @GetMapping("/{id}")   // http://localhost:8080/cartItem/1003   //  get   /cartItem/1004
    public ResultBean getById(@PathVariable("id") Integer id){
        System.out.println("-------CartItemController--------getById-------------");
        System.out.println(id);
        return cartItemService.getById(id);
    }

    @ApiOperation(value = "分页条件搜索")
    @PostMapping("/all")  //get /cartItem/all
    public ResultBean getAll(@RequestBody CartItemQuery cartItemQuery){
        System.out.println("-------CartItemController--------getAll-------------");
        return cartItemService.getAll(cartItemQuery);
    }

    @ApiOperation(value = "批量删除购物车信息")
    @PostMapping("/batch/{ids}")   // post + /food/batch
    public ResultBean batchDel(@PathVariable("ids") String ids){
        System.out.println("----------CartItemController---------batchDel---------------");
        System.out.println(ids); //接收到的参数格式 ： 21,19
        String[] strIds = ids.split(",");  //字符串拆分  [21,19]
        System.out.println(Arrays.toString(strIds));
        List<Integer> numids = new ArrayList<>();  //创建一个Integer集合  service层需要的参数类型
        for (String strid: strIds) {
            numids.add(Integer.parseInt(strid));//将数组中的每一项转型为Integer再加入到集合中
        }
        System.out.println(numids);
        return cartItemService.batchDel(numids);
    }
}
